// pages/shopform/shopform.js

var util = require('../../utils/util.js')
var config = require('../../config/config.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: config.foodStyles,
    objectArray: config.foodStylesObjectArray,
    shopId: 0,
    index: 0,
    shopName: '',
    starttime: '9:00',
    endtime: '21:00',
    shopTel:'',
    location:'',
    editLocation: false,
    notice: '',
    shopLogo: '../../imgs/default_shop_logo.png',
    selectLogo: false,
    latitude: 0,
    longitude: 0,
    showShopNameTip: false,
    showShopTelTip: false,
    showLocationTip: false,
    logoUrl: '',
    isEdit: false,
    authCode: '',

    multiArray: [config.regions, config.regionsMap[config.regions[0]]],
    objectMultiArray: config.objectRegions,
    multiIndex: [0, 0],

  },

  bindMultiPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = config.regionsMap[config.regions[0]]
            break
          case 1:
            data.multiArray[1] = config.regionsMap[config.regions[1]]
            break
          case 2: 
            data.multiArray[1] = config.regionsMap[config.regions[2]]
            break
          case 3: 
            data.multiArray[1] = config.regionsMap[config.regions[3]]
            break
        }
        data.multiIndex[1] = 0;
        break;
    }
    this.setData(data);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let shop_id = options.shop_id
    this.setData({
      authCode: options.auth_code
    })
    let that = this
    wx.request({
      url: `${config.requestBaseUrl}/Shop/getShopInfo`,
      method: 'POST',
      data: {
        shop_id: shop_id,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        let index = 0
        for (let i = 0, len = that.data.array.length; i < len; i++) {
          if (that.data.array[i] == res.data.shop_style)
            index = i
        }
        if (res.data.code === 1) {
          console.log(res)
          that.setData({
            shopId: shop_id,
            starttime: res.data.open_time,
            endtime: res.data.end_time,
            latitude: res.data.latitude,
            longitude: res.data.longitude,
            location: res.data.location,
            logoUrl: res.data.logo_url,
            shopLogo: res.data.logo_url,
            notice: res.data.notice,
            shopName: res.data.shop_name,
            index: index,
            shopTel: res.data.tel,
            isEdit: true,
            multiArray: [config.regions, config.regionsMap[config.regions[res.data.region_index_0]]],
            multiIndex: [res.data.region_index_0, res.data.region_index_1],
          })
        } else {
          console.log("没有找到商户信息")
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  bindStartTimeChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      starttime: e.detail.value
    })
  },

  bindEndTimeChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endtime: e.detail.value
    })
  },

  chooseLocation: function (e) {
    this.setData({
      editLocation: false,
      showLocationTip: false
    })
    let that = this
    wx.chooseLocation({
      success: function(res) {
        // console.log(res)
        that.setData({
          location: res.address,
          latitude: res.latitude,
          longitude: res.longitude,
        })
        if (that.data.location == '') {
          that.setData({
            showLocationTip: true
          })
        }
      },
      fail: function(res) {
        console.log(res)
      },
      complete: function(res) {
        // console.log(res)
      },
    })
  },

  clickEditLocation: function() {
    this.setData({
      editLocation: true
    })
  },

  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        // console.log(res.tempFilePaths)
        that.setData({
          shopLogo: res.tempFilePaths[0],
          selectLogo: true
        });
      }
    })
  },

  uploadImg: function () {
    let that = this
    util.wxUploadFile(this.data.shopLogo, 
      successRes => {
        
        that.setData({
          logoUrl: successRes.fileUrl
        })
        // console.log(successRes)
        that.uploadInfoToServer()
      },
      failRes => {
        wx.hideLoading()
        // console.log(failRes)
      }
    )
  },

  uploadInfoToServer: function () {
    // console.log(this.data.shopName)
    // console.log(this.data.array[this.data.index])
    // console.log(this.data.starttime)
    // console.log(this.data.endtime)
    // console.log(this.data.shopTel)
    // console.log(this.data.location)
    // console.log(this.data.notice)
    // console.log(this.data.latitude)
    // console.log(this.data.longitude)
    // console.log(this.data.logoUrl)
    // console.log(this.data.authCode)
    // return
    wx.request({
      url: `${config.requestBaseUrl}/Shop/uploadShopInfo`,
      method: 'POST',
      data: {
        openid: wx.getStorageSync('openid'),
        shop_name: this.data.shopName,
        shop_style: this.data.array[this.data.index],
        location: this.data.location,
        open_time: this.data.starttime,
        end_time: this.data.endtime,
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        tel: this.data.shopTel,
        notice: this.data.notice,
        logo_url: this.data.logoUrl,
        region: this.data.multiArray[1][this.data.multiIndex[1]],
        region_index_0: this.data.multiIndex[0],
        region_index_1: this.data.multiIndex[1],
        area: this.data.multiArray[0][this.data.multiIndex[0]],
        auth_code: this.data.authCode
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1) {
          let shop_id = res.data.shop_id
          wx.showToast({
            title: '已完成',
            duration: 1500,
            success: function () {
              wx.navigateTo({
                url: `../restaurant/restaurant?shop_id=${shop_id}`,
              })
            }
          })
        } else {
          console.log(res.data)
        }
        
      }
    })

  },

  clickUploadInfo: function () {
    if (!this.checkShopName()) {
      return
    }
    if (!this.checkShopTel()) {
      return
    }
    if (!this.checkShopLocation()) {
      return
    }
    if (!this.checkShopLogo()) {
      return
    }
    console.log("满足条件，可以上传了")
    wx.showLoading({
      title: '上传中...',
    })

    if (this.data.logoUrl == this.data.shopLogo) {
      // 编辑模式没有修改logo图片
      this.uploadInfoToServer()
    } else {
      this.uploadImg()
    }
    
  },

  blurInputShopName: function (e) {
    this.setData({
      shopName: e.detail.value
    })
    if (this.data.shopName == '') {
      this.setData({
        showShopNameTip: true
      })
    } else {
      this.setData({
        showShopNameTip: false
      })
    }
  },

  blurInputShopTel: function (e) {
    this.setData({
      shopTel: e.detail.value
    })
    this.checkTelNum()
    if (!this.checkTelNum()) {
      this.setData({
        showShopTelTip: true
      })
    } else {
      this.setData({
        showShopTelTip: false
      })
    }
  },

  blurInputNotice: function (e) {
    this.setData({
      notice: e.detail.value
    })
  },

  blurInputLocation: function (e) {
    this.setData({
      location: e.detail.value
    })
  },

  checkShopName: function () {
    if (this.data.shopName == '') {
      this.setData({
        showShopNameTip: true
      })
      this.showTipModal("请输入商家名称")
      return false
    }
    return true
  },

  checkShopTel: function () {
    if (!this.checkTelNum()) {
      this.setData({
        showShopTelTip: true
      })
      this.showTipModal("请输入合法的商家电话")
      return false
    }
    return true
  },

  checkShopLocation: function () {
    if (this.data.location == '') {
      this.setData({
        showLocationTip: true
      })
      this.showTipModal("请选择商家位置")
      return false
    }
    return true
  },

  checkShopLogo: function () {
    if (!this.data.selectLogo && !this.data.isEdit) {
      this.showTipModal("请上传商家logo")
      return false
    }
    return true
  },

  showTipModal: function (tipInfo) {
    wx.showModal({
      content: tipInfo,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
        }
      }
    });
  },

  checkTelNum: function () {
    if (this.data.shopTel.length >= 0 && this.data.shopTel.length < 11) {
      return false
    }
    return true
  }






})